$.get("/study/api/info",{
    name:name
},function(data) {
    if (data.msg != "") {error_bar(data.msg);return}

    switch (data["type"])  {
        case "bili":
            // 哔哩哔哩
            content = JSON.parse(data["content"])
            $.get("/study/api/bv",{
                "bv":content["bv"]
            },function(data) {
                data = JSON.parse(data)
                for (let i in data.data.pages) {
                  ele = data.data.pages[i]
                  document.getElementById("table").innerHTML += TR
                                                                .replaceAll("PAGE",ele.page)
                                                                .replaceAll("NAME",ele.part)
                }
            })
            u = new URL(location.origin+"/bili-p/index.php")
            u.searchParams.append("bv", content["bv"])
            u.searchParams.append("otype","dplayer")
            u.searchParams.append("q",80)
            u.searchParams.append("p",location.hash.substring(1))
            newDP(u)
            setInterval("timeCheck()",5000)
    }
})
var dp = new Object()
function newDP(u) {
    const params = u.toString().substring(u.toString().indexOf("?")+1).split('&')
    console.log(params)
    const map = {
      av: '', bv: '', p: '1'
    }
    for (let i = 0; i < params.length; i++) {
      const pair = params[i].split('=')
      map[pair[0]] = pair[1]
    }
    fetch(`/bili-p/index.php?av=${map['av']}&bv=${map['bv']}&p=${map['p']}&format=mp4&q=80`).then(res => {
      if (res.ok) {
        res.json().then(data => {
          dp = new DPlayer({
            container: document.getElementById('dplayer'),
            video: {
              url: data.url.replace(/^https?\:\/\//i, 'https://'),
              type: 'auto'
            }
          })
          dp.on("timeupdate",function() {
            timechange()
          })
          dp.video.addEventListener("error",function() {
            error_bar("视频解析错误，点击确定后跳转到B站原视频播放，这个视频不计入网课时长，您仍可以尝试其他分集（大部分是会解析成功的）",function() {
                window.open("https://www.bilibili.com/video/"+content["bv"]+"?p="+map['p'])
            })
          })
        })
      }
    })
}

function jumpP(page) {
  location.hash = page
  location.reload()
}
var nowtime=lasttime=0;
function timeCheck() {
    nowtime = dp.video.currentTime
    d = nowtime-lasttime
    if (d>5) d=5
    incTime(d)
    if (lasttime < nowtime) {
        lasttime = nowtime
    }
}
function timechange() {
    if (dp.video.currentTime < nowtime) {
        incTime(nowtime - lasttime)
        lasttime = dp.video.currentTime
        nowtime = dp.video.currentTime
    }
    
}
function incTime(t) {
    $.post("/study/api/wlog",{
        t:t
    })
}